package com.kx.yooli.kx.wechat.config.virtual;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author john_sqwen-childe.wen
 * @date 2024/3/28
 * @PROJECT_NAME wechat
 * @description create VirtualThreadConfig by john_sqwen
 * and virtualConfig value is
 */
@Component
public class VirtualThreadConfig {
 //definition sleep method class
 final   AtomicInteger atomicInteger = new AtomicInteger();
 private  final Logger log = LoggerFactory.getLogger(VirtualThreadConfig.class);
 public  void runVirtualThread() {
     Runnable runnable = () -> {
         try {
             Thread.sleep(Duration.ofSeconds(1));
         } catch (InterruptedException e) {
             throw new RuntimeException(e);
         }
         log.info("Work Done -" + atomicInteger.incrementAndGet());
     };
     Instant start = Instant.now();
     //virtual threads
     try (var excutor = Executors.newVirtualThreadPerTaskExecutor()) {
         //get current thread name
        log.info(Thread.currentThread().getName());
        int count = Thread.activeCount();
         log.info(String.valueOf(count));
         //Java increases readability through the use of underlined numerical literals: 10:00:00 represents 100000
         for (int i = 0; i < 10_000; i++) {
             excutor.submit(runnable);
         }
         Instant finish = Instant.now();
         long timeElapsed = Duration.between(start, finish).toMillis();
         log.info("Total elapsed time : {}", timeElapsed);
     }
     //create virtualThread method two
     Thread.startVirtualThread(()->{
        log.info("virtual Thread create and start");
     });
     //create virtualThread method three
     Runnable runnable1 = () -> log.info("Virtual Thread has create");
     Thread virtualThread = Thread.ofVirtual().name("test1111").start(runnable1);
 }
//    public static void main(String[] args) {
//        VirtualThreadConfig virtualThreadConfig = new VirtualThreadConfig();
//        virtualThreadConfig.runVirtualThread();
//    }
}
